using XxSystem.FileManager.Controllers;
using XxSystem.FileManager.core;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers(
    o => {
        o.Filters.Add<MyFilter>();
        o.Filters.Add<CusExceptionFilter>();
        o.Filters.Add<CusResultFilter>();
    }
    ).ConfigureApiBehaviorOptions(options =>
{
    options.SuppressConsumesConstraintForFormFileParameters = true;
    options.SuppressInferBindingSourcesForParameters = true;
    options.SuppressModelStateInvalidFilter = true;
    options.SuppressMapClientErrors = true;
    //options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
    //    "https://httpstatuses.com/404";
}); ;
// Add services to the container.
builder.Services.AddControllersWithViews();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(cfg => {
    cfg.AddPolicy("default", p => {
        p.WithOrigins("*");
        p.WithHeaders("*");
    });
});

builder.Services.AddScoped<Func<string,IObjectService >> (sp => {
    return new ObjectServiceFactory(sp).Getter;
});


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors("default");


app.UseHttpsRedirection();


app.MapControllers();

app.UseStaticFiles(new StaticFileOptions
{
    ServeUnknownFileTypes = true    
});

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Map("/objects", app => {   
    app.Run(async ctx => {
        var getObjectSerivce = ctx.RequestServices.GetRequiredService<Func<string, IObjectService>>();
        var path = ctx.Request.Path.Value ?? "";
        if (string.IsNullOrWhiteSpace(path)) {
            await ctx.Response.WriteAsync("error 001");
            return;
        }
        var keys = path.Split('/');
        if (keys.Length<=1)
        {
            await ctx.Response.WriteAsync("error 002");
            return;
        }
        var objectService = getObjectSerivce(keys[0]);
        await objectService.Invoke(ctx);        
    });
});

Task.Factory.StartNew(() => {
    ConvertToTask.run();
});

app.Run();
